<?php 

class LessonController extends Zend_Controller_Action 
{
    function init()
    {
        $this->initView();
        Zend_Loader::loadClass('AuxDbTable');
        Zend_Loader::loadClass('User');
        Zend_Loader::loadClass('Lesson');
        Zend_Loader::loadClass('Group');
        Zend_Loader::loadClass('Authgroup');
        Zend_Loader::loadClass('Mainmenu');
        Zend_Loader::loadClass('Rights');
        Zend_Loader::loadClass('Authority'); 
        $this->view->baseUrl = $this->_request->getBaseUrl();
        $this->view->user = Zend_Auth::getInstance()->getIdentity();
        $this->view->statuss = array('scheduled'=>'Scheduled', 'yes'=>'Yes', 'no'=>'No');
        $this->view->types = array('group'=>'Group','individ'=>'Individual');
        
        $group = new Group();
        $cond = array('deleted!=1');
        if($this->view->user->authgroup_id==2) $cond[] = 'assigned_to='.$this->view->user->id;
        $this->view->studygroup_ids = $group->fetchAll($cond,'name');
        
        $user = new User();
        $this->view->teacher_ids = $user->fetchAll('authgroup_id=2','last_name');
    }
    
    function preDispatch()
    {
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity()) {
            $this->_redirect('auth/login');
        }
        $menu = new Mainmenu();
        $this->view->main_menu = $menu->getMenu($this->view->user->id);
    }

    function indexAction()
    {
        $Rights =  new Rights();
        
        $this->view->title = "Уроки";
        $this->view->content_title = "Уроки";
        $lesson = new Lesson(); 
        $teacher = new User(); 
        $group = new Group(); 
        
        $cond = array('deleted!=1');
        $groupid = (int)$this->_request->getParam('group', 0);
        if($groupid>0) $cond[] = 'studygroup_id='.$groupid;
        if($this->view->user->authgroup_id==2) $cond[] = 'teacher_id='.$this->view->user->id;
        
        $this->view->item = new stdClass();
        
        $this->view->item->from_date = $this->_request->getParam('from_date', 0)?$this->_request->getParam('from_date', 0):date('Y-m-01');
        $this->view->item->to_date = $this->_request->getParam('to_date', 0)?$this->_request->getParam('to_date', 0):date('Y-m-t');
        $this->view->item->teacher_id = $this->_request->getParam('teacher_id', 0)?$this->_request->getParam('teacher_id', 0):0;
        
        foreach($this->view->item as $key=>$value) {
            if($value) {
                switch($key) {
                    case 'from_date':
                        $cond[] = 'start_date >= "'.$value.'"';
                        break;
                    case 'to_date':
                        $cond[] = 'start_date <= "'.$value.'"';
                        break;
                    default :
                        $cond[] = $key.'="'.$value.'"';
                        break;
                }
            }
        }
        
        $this->view->items = $lesson->fetchAll($cond,'start_date DESC');
        
        foreach($this->view->items as $item) {
            $item->teacher_id = $teacher->getUser($item->teacher_id);
            $item->studygroup_id = $group->getGroupName($item->studygroup_id);
        }
        
        $this->view->can_add = $Rights->CanDo($this->view->user->id,'lesson','add');
        $this->view->can_edit = $Rights->CanDo($this->view->user->id,'lesson','edit');
        $this->view->can_delete = $Rights->CanDo($this->view->user->id,'lesson','delete');
        
        $this->render();
    }
    
    function validate($id,$params)
    {
        $valid = true;
        $obj = new Lesson();
        
        if(strlen($params['name'])==0)
        {
            $this->view->message .= 'Please, enter Name.<br>';
            $valid = false;
        }    
        if(strlen($params['start_date'])==0)
        {
            $this->view->message .= 'Please, enter Start_date.<br>';
            $valid = false;
        }    
        if(strlen($params['start_time'])==0)
        {
            $this->view->message .= 'Please, enter Start_time.<br>';
            $valid = false;
        }    
                
        
        //email
        $email_pattern = '/^[A-Z0-9\._\-]+@[A-Z0-9\.\-]+\.[A-Z]{2,6}$/i';
        
        //date 
        $date_pattern = '/^[0-9]{4}\-(?:0[1-9]|1[0-2])\-(?:[0-2]?[0-9]|3[0-1])$/';
        if(!preg_match($date_pattern,$params['start_date']))
        {
            $this->view->message .= 'Invalid start_date '.$params['start_date'].'. Format yyyy-mm-dd.<br>';
            $valid = false;
        } 
        //time
        $time_pattern = '/[0-2][0-9]:[0-5][0-9]/';
        if($params['start_time'] && !preg_match($time_pattern,$params['start_time']))
        {
            $this->view->message .= 'Invalid Start time '.$params['start_time'].'. Format hh:mm.<br>';
            $valid = false;
        } 
        if($params['end_time'] && !preg_match($time_pattern,$params['end_time']))
        {
            $this->view->message .= 'Invalid End time '.$params['end_time'].'. Format hh:mm.<br>';
            $valid = false;
        }
        return $valid;
    }
    function addAction()
    {
        $Rights = new Rights();
        if(!$Rights->CanDo($this->view->user->id,'lesson','add')) $this->_redirect(DEFAUL_URL);
        
        $this->view->content_title = $this->view->title = "Add New Lesson";
        $params = array();

        if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
            Zend_Loader::loadClass('Zend_Filter_StripTags');
            $filter = new Zend_Filter_StripTags();
            
            $params['name'] = trim($filter->filter($this->_request->getPost('name')));
            $params['teacher_id'] = trim($filter->filter($this->_request->getPost('teacher_id')));
            $params['status'] = trim($filter->filter($this->_request->getPost('status')));
            $params['start_date'] = trim($filter->filter($this->_request->getPost('start_date')));
            $params['start_time'] = trim($filter->filter($this->_request->getPost('start_time')));
            if(trim($filter->filter($this->_request->getPost('end_time')))) $params['end_time'] = trim($filter->filter($this->_request->getPost('end_time')));
            $params['type'] = trim($filter->filter($this->_request->getPost('type')));
            $params['studygroup_id'] = trim($filter->filter($this->_request->getPost('studygroup_id')));
            $params['comments'] = trim($filter->filter($this->_request->getPost('comments')));
                    
            $this->view->message = '';
            if($this->validate(0,$params)) {
                $obj = new Lesson();
                $new_id = $obj->insert($params);
                
                $this->_redirect('/lesson');
                return;
            }
        } 
        
        // set up an "empty" lesson        
        $this->view->item = new stdClass();
        $this->view->item->id = null;
        $this->view->item->name = isset($params['name'])?$params['name']:'';
        $this->view->item->teacher_id = isset($params['teacher_id'])?$params['teacher_id']:'';
        $this->view->item->status = isset($params['status'])?$params['status']:'';
        $this->view->item->start_date = isset($params['start_date'])?$params['start_date']:date('Y-m-d');
        $this->view->item->start_time = isset($params['start_time'])?$params['start_time']:'';
        $this->view->item->end_time = isset($params['end_time'])?$params['end_time']:'';
        $this->view->item->type = isset($params['type'])?$params['type']:'';
        $this->view->item->studygroup_id = isset($params['studygroup_id'])?$params['studygroup_id']:'';
        $this->view->item->comments = isset($params['comments'])?$params['comments']:'';
                        
                    
        // additional view fields required by form
        $this->view->action = 'add';
        $this->render();
    }
    
    function editAction()
    {
        $Rights = new Rights();
        if(!$Rights->CanDo($this->view->user->id,'lesson','edit')) $this->_redirect(DEFAUL_URL);
            
        $this->view->content_title = $this->view->title = "Edit Lesson";
        $obj = new Lesson();
        
        if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
            Zend_Loader::loadClass('Zend_Filter_StripTags');
            $filter = new Zend_Filter_StripTags();
            
            $id = (int)$this->_request->getPost('id');
            $params = array();
            $params['name'] = trim($filter->filter($this->_request->getPost('name')));
            $params['teacher_id'] = trim($filter->filter($this->_request->getPost('teacher_id')));
            $params['status'] = trim($filter->filter($this->_request->getPost('status')));
            $params['start_date'] = trim($filter->filter($this->_request->getPost('start_date')));
            $params['start_time'] = trim($filter->filter($this->_request->getPost('start_time')));
            if(trim($filter->filter($this->_request->getPost('end_time')))) $params['end_time'] = trim($filter->filter($this->_request->getPost('end_time')));
            $params['type'] = trim($filter->filter($this->_request->getPost('type')));
            $params['studygroup_id'] = trim($filter->filter($this->_request->getPost('studygroup_id')));
            $params['comments'] = trim($filter->filter($this->_request->getPost('comments')));
                        
            if ($id !== false) {
                $this->view->message = '';
                if($this->validate($id,$params)) {
                    $where = 'id = ' . $id;
                    $obj->update($params, $where);
                
                    $this->_redirect('/lesson');
                    return;
                } else {
                    $this->view->item = $obj->fetchRow('id='.$id);
                    $this->view->item->id = $id;
                    
                    if( $params['name']) $this->view->item->name = $params['name'];
                    if( $params['teacher_id']) $this->view->item->teacher_id = $params['teacher_id'];
                    if( $params['status']) $this->view->item->status = $params['status'];
                    if( $params['start_date']) $this->view->item->start_date = $params['start_date'];
                    if( $params['start_time']) $this->view->item->start_time = $params['start_time'];
                    if( $params['end_time']) $this->view->item->end_time = $params['end_time'];
                    if( $params['type']) $this->view->item->type = $params['type'];
                    if( $params['studygroup_id']) $this->view->item->studygroup_id = $params['studygroup_id'];
                    if( $params['comments']) $this->view->item->comments = $params['comments'];
                                    
                }
            }
        } else {
            $id = (int)$this->_request->getParam('id', 0);
            if ($id > 0) {
                $this->view->item = $obj->fetchRow('id='.$id);
            }
        }

        // additional view fields required by form
        
        $user = new User();
        $this->view->teacher_ids = $user->fetchAll('authgroup_id=2','last_name');
        
        $this->view->action = 'edit';
        
        $this->render();
    }
    
    function deleteAction()
    {
        $Rights = new Rights();
        if(!$Rights->CanDo($this->view->user->id,'lesson','delete')) $this->_redirect(DEFAUL_URL);
        
        $this->view->content_title = $this->view->title = "Delete Lesson";
        
        $obj = new Lesson();
        if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
            Zend_Loader::loadClass('Zend_Filter_Alpha');
            $filter = new Zend_Filter_Alpha();
            
            $id = (int)$this->_request->getPost('id');
            $del = $filter->filter($this->_request->getPost('del'));
            
            if ($del == 'Yes' && $id > 0) {
                $data = array(
                        'deleted' => '1'
                );
                $where = 'id = ' . $id;
                $obj->update($data, $where);
            }
        } else {
            $id = (int)$this->_request->getParam('id');
            if ($id > 0) {
                // only render if we have an id and can find the lesson.
                $this->view->item = $obj->fetchRow('id='.$id);
                
                if ($this->view->item->id > 0) {
                    $this->render();
                    return;
                }
            }
        }
        
        // redirect back to the project list unless we have rendered the view
        $this->_redirect('/lesson');
    }
    
}